<template>
  <div class="vditor-container" ref="editorContainer"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'

const props = defineProps<{
  modelValue: string
  placeholder?: string
  height?: string
  width?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

const editorContainer = ref<HTMLElement | null>(null)
let vditor: any = null

// 初始化编辑器
onMounted(() => {
  if (!editorContainer.value) return

  // 检测是否为Mac系统
  const isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform)
  
  // 定义自定义工具栏
  const customToolbar = [
    {
      name: 'undo',
      tip: `撤销 ${isMac ? '⌘Z' : 'Ctrl+Z'}`,
      tipPosition: 's'
    },
    {
      name: 'redo',
      tip: `重做 ${isMac ? '⇧⌘Z' : 'Ctrl+Shift+Z'}`,
      tipPosition: 's'
    },
    '|',
    {
      name: 'emoji',
      tip: '表情',
      tipPosition: 's'
    },
    {
      name: 'headings',
      tip: '标题',
      tipPosition: 's'
    },
    {
      name: 'bold',
      tip: `粗体 ${isMac ? '⌘B' : 'Ctrl+B'}`,
      tipPosition: 's'
    },
    {
      name: 'italic',
      tip: `斜体 ${isMac ? '⌘I' : 'Ctrl+I'}`,
      tipPosition: 's'
    },
    {
      name: 'strike',
      tip: `删除线 ${isMac ? '⇧⌘X' : 'Ctrl+Shift+X'}`,
      tipPosition: 's'
    },
    {
      name: 'link',
      tip: `链接 ${isMac ? '⌘K' : 'Ctrl+K'}`,
      tipPosition: 's'
    },
    '|',
    {
      name: 'list',
      tip: `无序列表 ${isMac ? '⇧⌘8' : 'Ctrl+Shift+8'}`,
      tipPosition: 's'
    },
    {
      name: 'ordered-list',
      tip: `有序列表 ${isMac ? '⇧⌘7' : 'Ctrl+Shift+7'}`,
      tipPosition: 's'
    },
    {
      name: 'check',
      tip: `任务列表 ${isMac ? '⇧⌘9' : 'Ctrl+Shift+9'}`,
      tipPosition: 's'
    },
    {
      name: 'outdent',
      tip: '减少缩进',
      tipPosition: 's'
    },
    {
      name: 'indent',
      tip: '增加缩进',
      tipPosition: 's'
    },
    '|',
    {
      name: 'quote',
      tip: `引用 ${isMac ? '⇧⌘>' : 'Ctrl+Shift+>'}`,
      tipPosition: 's'
    },
    {
      name: 'line',
      tip: `分割线 ${isMac ? '⇧⌘-' : 'Ctrl+Shift+-'}`,
      tipPosition: 's'
    },
    {
      name: 'code',
      tip: `代码块 ${isMac ? '⇧⌘K' : 'Ctrl+Shift+K'}`,
      tipPosition: 's'
    },
    {
      name: 'inline-code',
      tip: `行内代码 ${isMac ? '⌘E' : 'Ctrl+E'}`,
      tipPosition: 's'
    },
    {
      name: 'insert-before',
      tip: '在前插入',
      tipPosition: 's'
    },
    {
      name: 'insert-after',
      tip: '在后插入',
      tipPosition: 's'
    },
    '|',
    {
      name: 'upload',
      tip: '上传图片',
      tipPosition: 's'
    },
    {
      name: 'table',
      tip: '表格',
      tipPosition: 's'
    },
    '|',
    {
      name: 'fullscreen',
      tip: '全屏',
      tipPosition: 's'
    },
    {
      name: 'outline',
      tip: '大纲',
      tipPosition: 's'
    },
    {
      name: 'word-counter',
      tipPosition: 'ne',
      tip: '字数统计',
      className: 'custom-word-counter',
      icon: '<span class="custom-word-counter">正文字数：0/10000</span>'
    }
  ]

  vditor = new Vditor(editorContainer.value, {
    height: props.height || '25rem',
    width: props.width || '100%',
    placeholder: props.placeholder || '请输入内容...',
    mode: 'wysiwyg', // 所见即所得模式
    counter: {
      enable: true,
      type: 'text',
      after: (count: number) => {
        // 直接更新字数统计元素
        updateWordCount(count)
        return ''
      }
    },
    input: (value: string) => {
      // 发送更新事件
      emit('update:modelValue', value)
      
      // 立即更新字数统计，不使用防抖
      const count = getWordCount(value)
      updateWordCount(count)
    },
    toolbar: customToolbar,
    cache: {
      enable: false,
    },
    preview: {
      hljs: {
        enable: true,
        style: 'github',
      },
    },
    upload: {
      accept: 'image/*',
      max: 5 * 1024 * 1024,
      handler: (files) => {
        // 这里可以实现图片上传
        console.log('上传图片', files)
        // 返回图片URL (单个字符串)
        return Promise.resolve('https://example.com/path/to/image.jpg')
      },
    },
    after: () => {
      // 编辑器初始化完成后设置内容
      vditor.setValue(props.modelValue)
      
      // 立即更新字数统计
      const count = getWordCount(props.modelValue)
      updateWordCount(count)
      
      // 添加输入事件监听器，实时更新字数统计
      const editorElement = editorContainer.value?.querySelector('.vditor-wysiwyg')
      if (editorElement) {
        editorElement.addEventListener('input', () => {
          const currentValue = vditor.getValue()
          const count = getWordCount(currentValue)
          updateWordCount(count)
        })
      }
    },
  })
})

// 获取字数统计
const getWordCount = (text: string): number => {
  if (!text) return 0
  
  try {
    // 移除HTML标签
    let plainText = text.replace(/<[^>]+>/g, '')
    
    // 移除Markdown标记
    plainText = plainText
      .replace(/!\[.*?\]\(.*?\)/g, '') // 移除图片
      .replace(/\[.*?\]\(.*?\)/g, '') // 移除链接
      .replace(/#+\s/g, '') // 移除标题标记
      .replace(/`{1,3}[\s\S]*?`{1,3}/g, '') // 移除代码块
      .replace(/\*\*|\*|~~|_/g, '') // 移除加粗、斜体、删除线等标记
      .replace(/\n+/g, ' ') // 将换行替换为空格
      .replace(/\s+/g, ' ') // 合并多个空格
      .trim()
    
    return plainText.length
  } catch (error) {
    console.error('字数统计出错:', error)
    
    // 如果处理出错，返回原始文本长度作为备用
    return text.length
  }
}

// 更新字数统计显示
const updateWordCount = (count: number) => {
  const counterElement = document.querySelector('.custom-word-counter')
  if (counterElement) {
    counterElement.textContent = `正文字数：${count}/10000`
  }
}

// 监听 modelValue 变化更新编辑器内容
watch(() => props.modelValue, (newValue) => {
  if (vditor && newValue !== vditor.getValue()) {
    vditor.setValue(newValue)
    
    // 更新字数统计
    const count = getWordCount(newValue)
    updateWordCount(count)
  }
})

// 组件销毁时清理资源
onBeforeUnmount(() => {
  if (vditor) {
    vditor.destroy()
  }
})
</script>

<style>
.vditor-container {
  width: 100%;
  border-radius: 0;
  overflow: hidden;
}

.vditor {
  border: none !important;
}

.vditor-reset {
  font-size: 16px !important;
}

.vditor-toolbar {
    background-color: #ffffff !important;
    border-bottom: none !important;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding: 0 !important;
    width: 100%;
    position: relative;
}

.vditor-toolbar__item .vditor-tooltipped{
    width: 30px;
}

.vditor-wysiwyg pre.vditor-reset:focus{
    background-color: #ffffff !important;
}

.vditor-wysiwyg pre.vditor-reset{
  padding: 0px 5px !important;
}

.vditor-toolbar__item--current svg {
  fill: #2563eb !important;
}

.vditor-ir__preview {
  border: none !important;
}

/* 自定义字数统计样式 */
.custom-word-counter {
  font-size: 14px;
  color: #64748b;
  margin-left: auto;
  padding: 0 ;
  white-space: nowrap;
  position: absolute;
  right: 0;
}
.vditor-counter{
  display: none;
}
/* 移除编辑区域的边框 */
.vditor-wysiwyg {
  border: none !important;
  background-color: #ffffff !important;
}

/* 自定义工具栏提示样式 */
.vditor-tooltip {
  max-width: none !important;
  font-size: 12px !important;
  padding: 4px 8px !important;
  background-color: rgba(0, 0, 0, 0.8) !important;
  color: white !important;
  border-radius: 4px !important;
  z-index: 1000 !important;
  white-space: nowrap !important;
  opacity: 1 !important;
  transform: translateY(8px) !important;
}

/* 工具栏提示箭头 */
.vditor-tooltip::before {
  border-color: transparent transparent rgba(0, 0, 0, 0.8) transparent !important;
}

/* 修复工具栏提示位置 */
.vditor-toolbar__item {
  position: relative !important;
}

/* 隐藏原始字数统计 */
.vditor-counter {
  display: none !important;
}
</style>
  